<template>
  <el-drawer
    :show-close="false"
    :size="1000"
    :wrapperClosable="false"
    :visible.sync="$attrs.visable"
    :before-close="handleClose"
  >
    <template slot="title">
      <div>
        <i class="el-icon-close f-16 mr-12 commhover" @click="handleClose"></i>
        <span class="f-16 c_text2">合并素材</span>
      </div>
    </template>
    <div class="h_full">
      <div class="mer_body flex">
        <div class="mergebox border-r">
          <div class="h_header flexbetween f-14 c_text2">基本信息</div>
          <!-- <div></div> -->
          <el-form
            :model="form"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            label-position="top"
            class="m-content p-12"
          >
            <el-form-item label="素材标题：" prop="name">
              <el-input
                v-model="form.title"
                placeholder="输入合并后的新素材标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="标签：" prop="name">
              <el-autocomplete
                v-model="form.name"
                style="width: 100%;"
                :fetch-suggestions="querySearch"
                @keyup.enter.native="handleAddLable"
                placeholder="新建或搜索标签，回车键确认"
              ></el-autocomplete>
              <div v-if="form.labels.length" class="labelbox mt-15">
                <div
                  class="labelitem c_text ml-5 mb-5"
                  v-for="(item, index) in form.labels"
                  :key="index"
                >
                  {{ item.tagName }}
                  <i
                    class="el-icon-close ml-10 commhover"
                    @click="removeLable(index)"
                  ></i>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <!-- 已选素材 -->
        <div class="mergebox border-r">
          <div class="h_header flexbetween f-14 c_text2">已选素材</div>
          <div class="m-content p-12">
            <div
              class="sc_item f-14"
              v-for="(item, index) in list"
              :key="index"
            >
              <img
                src="@/assets/images/group_item.png"
                alt=""
                class="sc_icon"
              />
              <span>{{ item.meterialName }}</span>
              <div class="sc_peration flex">
                <div class="flex1 c_fff" v-if="index !== list.length - 1">
                  <i class="el-icon-arrow-down"></i>
                </div>
                <div class="flex1 c_fff"><i class="el-icon-download"></i></div>
                <div class="flex1 c_fff" v-if="index !== 0">
                  <i class="el-icon-arrow-up"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 内容 -->
        <div class="mergebox hc2">
          <div class="h_header flexbetween f-14 c_text2">
            <div>内容</div>
            <div class="c_text3">已选4条</div>
          </div>
          <div class="m-content p-12">
            <div
              class="parent-item mb-20"
              v-for="(item, index) in list"
              :key="index"
            >
              <div class="parent_header flexbetween">
                <div class="f-14">
                  <i class="el-icon-arrow-right mr-10"></i>
                  <el-checkbox
                    v-model="item.checked"
                    :indeterminate="item.isIndeterminate"
                    @change="handleCheckAllChange($event, index)"
                  ></el-checkbox>
                  <span class="pl-10">{{ item.meterialName }}</span>
                </div>
                <div class="c_text3">已选{{itemCheck(item)}}条</div>
              </div>
              <div class="parent_child pl-30">
                <div
                  class="mb-10 flex"
                  v-for="(child, cindex) in item.contentList"
                  :key="cindex"
                >
                  <el-checkbox
                    v-model="child.checked"
                    @change="handleChecked($event, index, cindex)"
                  ></el-checkbox>
                  <div class="msg-text f-14 ml-10">{{ child.contentJson || '' }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="mer_bottom flexend">
        <el-checkbox v-model="checked">合并后删除原素材</el-checkbox>
        <el-button size="small" @click="handleClose" class="ml-12"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="onHandMergeMaterial">合并成新素材</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import {
  fetchMeterialTags,
  createMeterialTag,
  createMeterial,
  deleteMeterialById
} from "@/api/market/material";
export default {
  data() {
    return {
      form: {
        title: "",
        name: "",
        labels: [],
      },
      rules: {},
      checked: false,
      list: [],
      labelList: [],
    };
  },
  props: ['mergeList', 'meterialType'],
  mounted() {
    this.fetchMeterialTagList()
    this.list = this.mergeList.map(item => {
      item.checked = true
      item.isIndeterminate = true
      item.contentList = item.contentList.map(child => {
        return {...child, checked: true}
      })
      return item
    })
  },
  watch: {
    mergeList(mewList) {
      this.list = this.mergeList.map(item => {
        item.checked = true
        item.isIndeterminate = true
        item.contentList = item.contentList.map(child => {
          return {...child, checked: true}
        })
        return item
      })
    }
  },
  methods: {
    handleClose() {
      this.$emit("closeDrawer"); //关闭弹窗;
    },

    async fetchMeterialTagList() {
      try {
        let data = await fetchMeterialTags()
        if (data.code === 200) {
          this.labelList = data?.rows || []
          return data?.rows
        }
      } catch (error) {
        this.$message.error("系统异常");
      }
    },

    handleAddLable() {
      if (this.form.name) {
        if (this.form.labels.includes(this.form.name)) {
          this.$message.warning("标签重复");
          return;
        }
        this.form.labels.push(this.form.name);
        this.form.name = "";
      }
    },

    removeLable(index) {
      this.form.labels.splice(index, 1);
    },

    handleCheckAllChange(val, index) {
      this.list[index].isIndeterminate = false;
      this.list[index].contentList.forEach((i) => {
        i.checked = val;
      });
    },

    handleChecked(val, index, cindex) {
      let arr = this.list[index].contentList.filter(item => item.checked);
      if (arr.length == this.list[index].contentList.length) {
        this.list[index].checked = true;
        this.list[index].isIndeterminate = false;
      } else {
        if (arr.length) {
          this.list[index].isIndeterminate = true;
        }
        this.list[index].checked = false;
      }
    },
    itemCheck(item) {
      let arry = item.contentList.filter(child => {
        return child.checked === true
      })
      return arry.length
    },
    querySearch(queryString, cb) {
      let results = []
      if (queryString) {
        const findout = this.labelList.filter(this.createFilter(queryString))
        results = findout.map(x => ({...x, value: x.tagName}))
      } else {
        results = this.labelList.map(x => ({...x, value: x.tagName}))
      }
      cb(results);
    },

    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.tagName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    async handleAddLable() {
      if (this.form.name) {
        if (this.form.labels.includes(this.form.name)) {
          this.$message.warning("标签重复");
          return;
        }
        await this.onCreateMeterialTag(this.form.name)
        this.form.name = "";
      }
    },

    async onCreateMeterialTag(tagName) {
      let result = this.labelList.find(item => item?.tagName === tagName)
      if (!result) {
        await createMeterialTag({tagName})
        let result = await this.fetchMeterialTagList()
        let rowItem = result.find(item => item?.tagName === tagName)
        this.form.labels.push(rowItem)
      }else {
        this.form.labels.push(result)
      }
    },

    async onHandMergeMaterial() {
      let contentList = []
      this.mergeList.map(item => {
        contentList.push(...item.contentList.filter(child => child.checked))
      })
      let data = {
        meterialType: this.meterialType,
        meterialName: this.form.title,
        tagIds: this.form.labels.map(item => (item.id)).toString(),
        contentList,
      }
      if (this.form.title.length === 0) {
        this.$message.error("素材标题不为空")
        return
      }
      if (contentList.length === 0) {
        this.$message.error("素材内容不为空")
        return
      } 
      await createMeterial(data)
      if (this.checked) {
        let ids = this.mergeList.map(item => {
          return item.id
        }).toString();
        await deleteMeterialById(ids)
      }
      this.$emit("closeDrawer");
    }
  },
};
</script>
<style lang="scss" scoped>
.mer_body {
  height: calc(100% - 60px);
}
.mer_bottom {
  height: 60px;
  padding: 0 12px;
  border-top: 1px solid #e9e9e9;
}
.mergebox {
  width: 240px;
}
.hc2 {
  width: 520px;
}
.h_header {
  height: 40px;
  padding: 0 12px;
  background: #f7f7f7;
  border-bottom: 1px solid #e9e9e9;
}
.border-r {
  border-right: 1px solid #e9e9e9;
}
.m-content {
  height: calc(100% - 40px);
  overflow-y: auto;
}
.labelbox {
  border: 1px solid rgb(240, 240, 240);
  padding: 8px;
}
.labelitem {
  display: inline-block;
  border: 1px solid #d9d9d9;
  background-color: #f5f5f5;
  padding: 4px 13px;
  line-height: 22px;
}
::v-deep .el-form-item__label {
  line-height: 26px;
}
.sc_item {
  position: relative;
  padding: 9px 8px;
  background: #fafafa;
  border-radius: 2px;
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.sc_icon {
  width: 14px;
  margin-right: 8px;
}
.sc_peration {
  opacity: 0;
  position: absolute;
  right: 4px;
  top: 8px;
  height: 24px;
  background: rgba(0, 0, 0, 0.85);
  border-radius: 2px;
  color: #fff;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  & > div {
    width: 25px;
    height: 25px;
    line-height: 25px;
    text-align: center;
  }
}
.sc_item:hover .sc_peration {
  opacity: 1;
}
.parent_header {
  position: relative;
  margin-bottom: 10px;
  background-color: #f7f7f7;
  display: flex;
  justify-content: space-between;
  padding: 8px 12px;
}
.msg-text {
  max-width: 360px;
  width: fit-content;
  padding: 6px 12px;
  color: #000;
  border: 1px solid #e9e9e9;
  border-radius: 5px;
}
</style>